﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Common;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using Taobao.Top.Api.Domain;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;

public partial class top_crm_taobaogrouplist : System.Web.UI.Page
{
    public string session = string.Empty;
    public string nick = string.Empty;
    public string id = string.Empty;
    public string now = string.Empty;
    public string totalcustomer = string.Empty;
    public string act = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        id = utils.NewRequest("id", utils.RequestType.QueryString);
        string act = utils.NewRequest("act", utils.RequestType.QueryString);
        Common.Cookie cookie = new Common.Cookie();
        string taobaoNick = cookie.getCookie("nick");
        session = cookie.getCookie("top_sessiongroupbuy");
        string iscrm = cookie.getCookie("iscrm");
        Rijndael_ encode = new Rijndael_("tetesoft");
        nick = encode.Decrypt(taobaoNick);

        //过期判断
        if (string.IsNullOrEmpty(taobaoNick))
        {
            string msg = "尊敬的淘宝卖家，非常抱歉的告诉您，您还没有购买此服务或者登录信息已失效，如需继续使用请<a href='http://fuwu.taobao.com/serv/detail.htm?service_id=4545' target='_blank'>进入该服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }


        //过期判断
        if (!IsBuy(nick))
        {
            string msg = "尊敬的" + nick + "，非常抱歉的告诉您，只有VIP版本才能使用【客户关系营销】功能，如需继续使用请<a href='http://fuwu.taobao.com/ser/detail.htm?service_code=service-0-22904&frm=haoping' target='_blank'>购买高级会员服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }

        if (!IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        IDictionary<string, string> param = new Dictionary<string, string>();

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.grade.get", session, param);
        Regex reg = new Regex(@"<grade_promotion>([\s\S]*?)</grade_promotion>", RegexOptions.IgnoreCase);
        MatchCollection match = reg.Matches(result);
        //Response.Write(result);

        for (int i = 1; i <= match.Count; i++)
        {
            string str = match[i - 1].Groups[0].ToString();

            ((TextBox)this.FindControl("tbZhekou" + i.ToString())).Text = (double.Parse(GetValueByProperty(str, "discount")) / 100).ToString();
            ((TextBox)this.FindControl("tbCount" + i.ToString())).Text = GetValueByProperty(str, "next_upgrade_count");
            ((TextBox)this.FindControl("tbAmount" + i.ToString())).Text = (double.Parse(GetValueByProperty(str, "next_upgrade_amount")) / 100).ToString();

            if (GetValueByProperty(str, "next_upgrade_count") != "0" || (double.Parse(GetValueByProperty(str, "next_upgrade_amount")) / 100).ToString() != "0")
            {
                ((CheckBox)this.FindControl("cbAuto" + i.ToString())).Checked = true;
            }
        }
    }

    public static string GetValueByProperty(string str, string prop)
    {
        Regex reg = new Regex(@"<" + prop + @">([^<]*)</" + prop + @">", RegexOptions.IgnoreCase);
        if (reg.IsMatch(str))
        {
            return reg.Match(str).Groups[1].ToString();
        }
        else
        {
            return "";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        string amountList = string.Empty;
        string countList = string.Empty;
        string discountList = string.Empty;
        string hierarchyList = "true,";

        for (int i = 1; i <= 4; i++)
        {
            string discount = (double.Parse(((TextBox)this.FindControl("tbZhekou" + i.ToString())).Text) * 100).ToString();
            discountList += discount + ",";
        }

        for (int i = 1; i < 4; i++)
        {
            string amount = ((TextBox)this.FindControl("tbAmount" + i.ToString())).Text;
            string count = ((TextBox)this.FindControl("tbCount" + i.ToString())).Text;
            string hierarchy = ((CheckBox)this.FindControl("cbAuto" + i.ToString())).Checked.ToString().ToLower();

            if (hierarchy == "true")
            {
                if (amount == "" || amount == "0")
                {
                    amountList += ",";
                }
                else
                {
                    amountList += (double.Parse(amount) * 100).ToString() + ",";
                }

                if (count == "" || count == "0")
                {
                    countList += ",";
                }
                else
                {
                    countList += count + ",";
                }
            }
            hierarchyList += hierarchy + ",";
        }

        discountList = discountList.Substring(0, discountList.Length - 1);
        hierarchyList = hierarchyList.Substring(0, hierarchyList.Length - 1);

        IDictionary<string, string> param = new Dictionary<string, string>();

        if (amountList != "")
        {
            amountList = amountList.Substring(0, amountList.Length - 1);
            param.Add("amount", amountList);
        }

        if (countList != "")
        {
            countList = countList.Substring(0, countList.Length - 1);
            param.Add("count", countList);
        }


        param.Add("grade", "1,2,3,4");
        param.Add("discount", discountList);
        param.Add("hierarchy", hierarchyList);

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.grade.set", session, param);
        //Response.Write(hierarchyList + "<br>");
        //Response.Write(result);
        Response.Write("<script>alert('修改成功！');window.location.href='taobaogrouplist.aspx'</script>");
    }

    /// <summary>
    /// 判断该用户是否订购了该服务
    /// </summary>
    /// <param name="nick"></param>
    /// <returns></returns>
    private bool IsBuy(string nick)
    {
        string sql = "SELECT plus FROM TCS_ShopSession WHERE nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count != 0)
        {
            string plus = dt.Rows[0][0].ToString();
            if (plus.IndexOf("crm") != -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }


    #region TOP API
    /// <summary> 
    /// 给TOP请求签名 API v2.0 
    /// </summary> 
    /// <param name="parameters">所有字符型的TOP请求参数</param> 
    /// <param name="secret">签名密钥</param> 
    /// <returns>签名</returns> 
    protected static string CreateSign(IDictionary<string, string> parameters, string secret)
    {
        parameters.Remove("sign");
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
        StringBuilder query = new StringBuilder(secret);
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        query.Append(secret);
        MD5 md5 = MD5.Create();
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }
        return result.ToString();
    }
    /// <summary> 
    /// 组装普通文本请求参数。 
    /// </summary> 
    /// <param name="parameters">Key-Value形式请求参数字典</param> 
    /// <returns>URL编码后的请求数据</returns> 
    protected static string PostData(IDictionary<string, string> parameters)
    {
        StringBuilder postData = new StringBuilder();
        bool hasParam = false;
        IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
        while (dem.MoveNext())
        {
            string name = dem.Current.Key;
            string value = dem.Current.Value;
            // 忽略参数名或参数值为空的参数 
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                if (hasParam)
                {
                    postData.Append("&");
                }
                postData.Append(name);
                postData.Append("=");
                postData.Append(Uri.EscapeDataString(value));
                hasParam = true;
            }
        }
        return postData.ToString();
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string Post(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "xml");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    #endregion
}